<?php

namespace App\Console\Commands;

use App\Constant\JpushCode;
use App\Constant\SmsTemplate;
use App\Events\JpushNoticeEvent;
use App\Models\UserCertOcr;
use Carbon\Carbon;
use Illuminate\Console\Command;

class JpushBirthdayCommand extends Command {
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'birthday:cron';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '生日推送';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct() {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle() {
        $now = Carbon::now()->format('md');
        $res = UserCertOcr::with(['userGlobalRelation', 'user'])
            ->whereIsValid(UserCertOcr::IS_VALID)
            ->where(\DB::raw('substring(`num`,11,4)'), $now)
            ->get();

        $relationIds = $phones = [];
        foreach ($res as $v) {
            if ($v->userGlobalRelation->jpush_registration_id && $v->user->phone_num) {
                $relationIds[] = $v->userGlobalRelation->jpush_registration_id;
                $phones[]      = $v->user->phone_num;
            } else {
                continue;
            }
        }
        \Log::debug('生日推送手机号:' . json_encode($phones, JSON_UNESCAPED_UNICODE));
        \Log::debug('生日推送关联id:' . json_encode($relationIds, JSON_UNESCAPED_UNICODE));

        if (!empty($relationIds)) {
            //极光推送数据
            $data = [
                'body'     => 'happy birthday',
                'title'    => 'happy',
                'audience' => JpushCode::AUDIENCE_TYPE_TWO,
                'to'       => $relationIds,
                'extras'   => [
                    'jump_type' => JpushCode::EXTRAS_JUMP_TYPE_ONE
                ]
            ];
            event(new JpushNoticeEvent($data));
        }
        if (!empty($phones)) {
            //短信推送
            foreach ($phones as $v) {
                SmsTemplate::send(SmsTemplate::TEMPLATE_SMS_USER_BIRTHDAY, $v);
            }
        }
        return true;
    }
}
